import React from 'react'
import { Form, Input, Button, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { Redirect } from 'react-router-dom'

import './login.css'
import { reqLogin } from '../../api'
import storage from '../../utils/storageUtil'

export default class Login extends React.Component {

    onFinish = async v => {
        const data = await reqLogin(v.username, v.password)
        console.log(data)
        if(data.status === 0){
            storage.addUserStorage(data.data)
            this.props.history.replace('/')
        }else{
            message.error(data.msg)
        }
    };

    render() {
        if(storage.getUserStorage().username){
            return(
                <Redirect to='/'/>
            )
        }
        return (
            <div className='login'>
                <div className='login-container'>
                    <h1>用户登录</h1>
                    <Form
                        className="login-form"
                        initialValues={{ remember: true }}
                        onFinish={this.onFinish}
                    >
                        <Form.Item
                            name="username"
                            rules={[{ required: true, message: '请输入用户名!' }]}
                        >
                            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
                        </Form.Item>
                        <Form.Item
                            name="password"
                            rules={[{ required: true, message: '请输入密码!' }]}
                        >
                            <Input
                                prefix={<LockOutlined className="site-form-item-icon" />}
                                type="password"
                                placeholder="密码"
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" className="login-form-button">
                                登录
                        </Button>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        )
    }
}